import ProcessBarUpload from '@/pages/pc/components/Upload/ProcessBarUpload';
import { message, Input } from 'antd';
import { isImg } from '@/utils';
import type { FC } from 'react';
import { useEffect, useRef, useState } from 'react';
import styles from './index.less';
import { allGet } from '@/services/pc';
import { apiUrl } from '@/common/const';

type ValueType = {
  path?: string;
  aid?: number | string;
  limit?: number | string;
};

interface Props {
  value?: ValueType[];
  onChange?: (value?: ValueType[]) => void;
  payload?: any;
}

const Index: FC<Props> = ({ value, onChange, payload = {} }) => {
  const defaultItem = useRef<any>({
    path: undefined,
    aid: undefined,
    limit: undefined,
  });
  const [val, setVal] = useState<ValueType[]>([defaultItem.current]);
  const valRef = useRef([defaultItem.current]);
  //宣传视频的值
  //const promotionalVideoRef = useRef<any>([]);
  const handlePromotionalVideoBeforeUpload = async (file, preFile) => {
    if (!isImg(file.name)) {
      message.error('仅支持图片');
      return false;
    }
    // if (preFile && preFile.aid) {
    //   if (!(await handleRemovePic(preFile))) return false; // 删除实物图片
    // }
    return true;
  };
  const update = (value) => {
    if (onChange) {
      onChange(value);
    } else {
      setVal(value);
    }
  };
  const _onChange = (index, evt) => {
    const newVal = [...valRef.current];
    newVal[index].limit = evt.target.value?.replace(/^(0+)|[^\d]+/g, '');
    update(newVal);
  };

  const handleRemovePic = async (file) => {
    await allGet({
      params: { mod: 'attachment', do: 'delete', aid: file.aid, version: 'pc1.0' },
    });
    // if (reponse.success) {
    //   return true;
    // }
    return false;
  };
  const onRemove = async (index) => {
    // if (!(await handleRemovePic(··val[index]))) return; // 删除实物图片
    const pre = valRef.current.slice(0, index);
    const suf = valRef.current.slice(index + 1);
    console.log(pre, suf);
    if (suf.length === 0) {
      defaultItem.current = {};
    }
    update([...pre, ...suf]);
  };
  useEffect(() => {
    setVal(!value || !value.length ? [defaultItem.current] : value);
    valRef.current = !value || !value.length ? [defaultItem.current] : value;
  }, [value]);

  const handleUploadSuccess = (file, index) => {
    const { response, ...others } = file;
    const newValue: any[] = [...valRef.current];
    newValue[index] = { ...newValue[index], ...others, ...(response?.data ?? {}) };
    update(newValue);
  };

  const handleUploadChange = (file, index) => {
    const { response, name, ...others } = file;
    const newValue: any[] = [...valRef.current];
    newValue[index] = { ...newValue[index], ...others, name, ...(response?.data ?? {}) };
    update(newValue);
  };
  return (
    <div className={styles.container}>
      {val.map((item, index) => {
        return (
          <div>
            <ProcessBarUpload
              payload={payload}
              className={styles.promotionalVideo}
              prefix={<i className="icon-file-link" />}
              tips="点击上传实物图片"
              onBeforeUpload={handlePromotionalVideoBeforeUpload}
              action={apiUrl}
              name="Filedata"
              controlled
              onSuccess={(_, file) => handleUploadSuccess(file, index)}
              onChange={(_, file) => handleUploadChange(file, index)}
              value={[item]}
            />
            <Input
              className={styles.input}
              onChange={(evt) => {
                _onChange(index, evt);
              }}
              value={item.limit}
              placeholder="填写赠送数量"
              type="number"
            />
            <i className={styles.remove} onClick={() => onRemove(index)}>
              X
            </i>
          </div>
        );
      })}
    </div>
  );
};

export default Index;
